package com.atguigu.tingshu.account.consumer;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 账户初始化消息的消费者
 *
 * @author Haoran Sun
 * @since 2024/08/17
 */

@Component
@Slf4j
public class AccountInitConsumer {


    @Resource
    private UserAccountService userAccountService;

    /**
     * 用户账户初始化
     *
     * @param userId 用户id
     */
    @RabbitListener(queues = "account_queue")
    public void initAccountConsumer(Long userId, Channel channel, Message message) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            userAccountService.initAccount(userId);
            log.info("用户账户初始化成功，用户id：{}", userId);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("用户账户初始化失败，用户id：{}。", userId);
            try {
                if (message.getMessageProperties().getRedelivered()) {
                    // 消息第二次消费失败
                    log.error("消息第二次消费失败，消息不再重新入队");
                    channel.basicReject(deliveryTag, false);
                } else {
                    // 消息第一次消费失败
                    log.error("消息第一次消费失败，消息重新入队");
                    channel.basicReject(deliveryTag, true);
                }
            } catch (Exception ex) {
                log.error("消息确认发送失败");
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }

}
